<template>
  <div>
    <a-row class="table-operations">
      <a-col :span="2" :offset="22">
        <a-button type="primary" icon="reload" @click="refresh">刷新</a-button>
      </a-col>
    </a-row>
    <a-table
      rowKey="id"
      :columns="columns"
      :data-source="stuffList.dataList"
      :pagination="stuffList.pagination"
      :loading="loading"
      @change="handleTableChange">
      <span slot="imgSlot" slot-scope="text,record">
        <img style="width:50px; height:50px" :src="`${imgBaseURL}${record.img}`" />
      </span>
      <template slot="operation" slot-scope="record">
        <a @click="editStuff(record)">编辑</a>
      </template>
    </a-table>
    <a-modal
      width="400px"
      centered
      title="编辑物品"
      :visible="modal.visible"
      :confirmLoading="modal.confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel">
      <a-form :form="form" layout="horizontal" :label-col="{span:4}" :wrapper-col="{span:18}">
        <a-form-item>
          <a-row>
            <a-col :offset="11">
              <a-upload
                name="avatar"
                list-type="picture-card"
                class="picture-uploader"
                :showUploadList="false"
                :customRequest="handleImgChange"
              >
                <img
                  v-if="`${imgBaseURL}${modal.img}`"
                  :src="`${imgBaseURL}${modal.img}`"
                  :style="{height:'100%', width:'100%'}"
                  alt="stuff-picture"
                />
                <div v-else>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item label="名称">
          <a-input
            v-decorator="['name', {
              rules: [{ required: true, message: '请输入名字!' }],
              initialValue: modal.name
            }]"
            placeholder="请输入" />
        </a-form-item>
        <div class="same-row-item">
          <a-form-item label="单价" :label-col="{span:8}" :wrapper-col="{span:12}">
            <a-input
              v-decorator="['price', {
                rules: [{ required: true, message: '请输入单价!' }],
                initialValue: modal.price
              }]"
              placeholder="请输入" />
          </a-form-item>
          <a-form-item label="分类" :label-col="{span:8}" :wrapper-col="{span:12}">
            <a-input
              v-decorator="['type', {
                rules: [{ required: true, message: '请输入类型!' }],
                initialValue: modal.type
              }]"
              placeholder="请输入" />
          </a-form-item>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { getStuffList, updateStuff } from '@/api/stuffManage'
import { uploadPicture } from '@/api/common'
export default {
  name: 'StuffTable',
  props: {
    location: {
      type: Object,
      default: null
    },
    stuffType: {
      type: Object,
      default: null
    }
  },
  computed: {
    columns () {
      return [
        {
          title: '预览图',
          dataIndex: 'img',
          align: 'center',
          scopedSlots: { customRender: 'imgSlot' }
        },
        {
          title: '编码',
          dataIndex: 'code',
          align: 'center'
        },
        {
          title: '物品名',
          dataIndex: 'name',
          align: 'center',
          ellipsis: true
        },
        {
          title: '单价',
          dataIndex: 'price',
          align: 'center',
          sorter: true
        },
        {
          title: '库存',
          dataIndex: 'amount',
          align: 'center'
        },
        {
          title: '操作',
          align: 'center',
          scopedSlots: { customRender: 'operation' }
        }
      ]
    }
  },
  data () {
    return {
      imgBaseURL: `http://114.132.236.225:8080/common/download?fileName=`,
      loading: false,
      stuffList: {
        dataList: [],
        name: null,
        sorter: null,
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showSizeChanger: true,
          pageSizeOptions: ['10', '15', '20'],
          showQuickJumper: true,
          showTotal: total => `总共 ${total} 条数据`
        }
      },
      modal: {
        visible: false,
        id: null,
        img: null,
        name: null,
        price: null,
        type: null,
        confirmLoading: false
      },
      form: this.$form.createForm(this, { name: 'stuffForm' })
    }
  },
  created () {
    this.getAllStuffList()
  },
  watch: {
    stuffType () {
      // 解决父组件的ref不能获取子组件方法的问题
      this.$nextTick(() => {
        this.getAllStuffList()
      })
    },
    deep: true
  },
  methods: {
    getAllStuffList () {
      const _this = this
      const sorter = _this.stuffList.sorter || {}
      this.loading = true
      getStuffList({
        location: _this.location.tab,
        type: _this.stuffType.tab,
        order: sorter.order,
        page: _this.stuffList.pagination.current,
        pageSize: _this.stuffList.pagination.pageSize
      }).then((res) => {
        _this.stuffList.dataList = res.data.list
        _this.stuffList.pagination.total = res.data.total
        _this.loading = false
      }).catch((err) => {
        _this.$message.error(err.response.data.msg || { content: '获取物品失败' })
        _this.loading = false
      })
    },
    refresh () {
      this.stuffList.pagination.current = 1
      this.getAllStuffList()
    },
    handleTableChange (pagination, filters, sorter) {
      this.stuffList.pagination = pagination
      this.stuffList.sorter = sorter
      this.getAllStuffList()
    },
    handleImgChange (file) {
      const _this = this
      const ImgData = new FormData()
      ImgData.append('file', file.file)
      uploadPicture(ImgData).then((res) => {
        _this.modal.img = res.data.fileName
      }).catch((err) => {
        _this.$message.error(err.response.data.msg || { content: '上传图片失败' })
      })
    },
    editStuff (record) {
      this.modal.id = record.id
      this.modal.name = record.name
      this.modal.price = record.price
      this.modal.type = record.type
      this.modal.img = record.img
      this.modal.visible = true
    },
    handleOk () {
      this.modal.confirmLoading = true
      const _this = this
      this.form.validateFields((err, values) => {
        if (!err) {
          updateStuff({
            id: _this.modal.id,
            img: _this.modal.img,
            price: values.price,
            name: values.name,
            type: values.type
          }).then((res) => {
            _this.modal.confirmLoading = false
            _this.handleCancel()
            _this.$message.success({ content: '修改物品成功' })
            _this.$emit('refresh') // 如果更改了分类，则需要父组件先刷新获取
            _this.getAllStuffList()
          }).catch((err) => {
            _this.$message.error(err.response.data.msg || { content: '修改物品失败' })
          })
        } else {
          _this.modal.confirmLoading = false
          _this.$message.error({ content: '修改物品失败' })
        }
      })
    },
    handleCancel () {
      this.form.resetFields()
      this.modal.visible = false
    }
  }
}
</script>

<style lang="less" scoped>
.same-row-item {
  display: flex;
}

.table-operations {
  margin-bottom: 10px;
}

//  直接选择不了
// :global(.ant-upload.ant-upload-select-picture-card) {
//   width: 100%;
// }

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #64b5f1;
}

.ant-upload-select-picture-card .ant-upload-text {
  color: #64b5f1;
}
/deep/ .ant-table-thead > tr > th {
  padding: 14px;
}
/deep/ .ant-table-tbody > tr > td {
  padding: 8px 10px;
}
</style>
